/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package clienttest;

import clienttest.common.ConnectManager;
import clienttest.object.CreditCard;
import clienttest.object.SavingAccountObject;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

/**
 *
 * @author lekhanhduy
 */
public class Login extends javax.swing.JFrame {

    private WindowAdapter windowAdapter;
    private AcountBank acountBank;
    private ConnectManager connectManager;

    /**
     * Creates new form NewJFrame
     */
    public Login(AcountBank acountBank) {
        initComponents();
        connectManager = new ConnectManager(this);
        this.acountBank = acountBank;
        this.setLocationRelativeTo(null);
        windowAdapter = new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent we) {
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        };
        this.addWindowListener(windowAdapter);
        CaretListener caret = new CaretListener() {

            @Override
            public void caretUpdate(CaretEvent e) {
                int passwordLength = jTxtPassWord.getText().length();
                if (passwordLength < 6) {
                    jTxtPassWord.setEditable(true);
                    validate();
                } else {
                    jTxtPassWord.setEditable(false);
                    validate();
                }
            }
        };

        KeyListener key = new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
                    jTxtPassWord.setEditable(true);
                };
            }
        };
        jTxtPassWord.addCaretListener(caret);
        jTxtPassWord.addKeyListener(key);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPnLogin = new javax.swing.JPanel();
        jTxtAccount = new javax.swing.JTextField();
        jLblAccountNumber = new javax.swing.JLabel();
        jLblPass = new javax.swing.JLabel();
        jBtnLogin = new javax.swing.JButton();
        jTxtPassWord = new javax.swing.JPasswordField();
        jChbSavingAccount = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTxtAccount.setToolTipText("");

        jLblAccountNumber.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLblAccountNumber.setText("Số tài khoản");

        jLblPass.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLblPass.setText("Mật khẩu");

        jBtnLogin.setText("Đăng nhập");
        jBtnLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnLoginActionPerformed(evt);
            }
        });

        jChbSavingAccount.setText("Tài khoản tiết kiệm");
        jChbSavingAccount.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jChbSavingAccountActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPnLoginLayout = new javax.swing.GroupLayout(jPnLogin);
        jPnLogin.setLayout(jPnLoginLayout);
        jPnLoginLayout.setHorizontalGroup(
            jPnLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPnLoginLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPnLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTxtPassWord)
                    .addGroup(jPnLoginLayout.createSequentialGroup()
                        .addGroup(jPnLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTxtAccount, javax.swing.GroupLayout.PREFERRED_SIZE, 277, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLblAccountNumber)
                            .addComponent(jLblPass))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPnLoginLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jChbSavingAccount)
                        .addGap(18, 18, 18)
                        .addComponent(jBtnLogin)))
                .addContainerGap())
        );
        jPnLoginLayout.setVerticalGroup(
            jPnLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPnLoginLayout.createSequentialGroup()
                .addGap(174, 174, 174)
                .addComponent(jLblAccountNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTxtAccount, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLblPass)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTxtPassWord, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPnLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBtnLogin)
                    .addComponent(jChbSavingAccount))
                .addContainerGap(221, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPnLogin, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPnLogin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBtnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnLoginActionPerformed
        String accountName = jTxtAccount.getText().toString();
        String pass = jTxtPassWord.getText().toString();
        if (!jChbSavingAccount.isSelected()) {
            if (pass.length() != 6) {
                JOptionPane.showMessageDialog(this,
                        "Mật khẩu phải đủ 6 ký tự!",
                        "Lỗi mật khẩu",
                        JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (connectManager.login(accountName, pass)) {
                CreditCard creditCard = connectManager.getCreditCardOfUser(accountName);
                if (creditCard != null && creditCard.getStaffBank()) {
                    //tao form hoi nguoi dung muon dang nhap la tai khoan thuong hay tai khoan quan ly
                    JPanel jpanel = new JPanel(new GridLayout(0, 1));
                    ButtonGroup bg = new ButtonGroup();
                    JRadioButton staffBank = new JRadioButton();
                    staffBank.setText("Tài khoản nhân viên");
                    staffBank.setSelected(true);
                    bg.add(staffBank);
                    JRadioButton users = new JRadioButton();
                    users.setText("Tài khoản thường");
                    bg.add(users);
                    jpanel.add(staffBank);
                    jpanel.add(users);

                    final int option = JOptionPane.showConfirmDialog(this, jpanel, "Lựa chọn phiên làm việc!", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                    if (option == JOptionPane.OK_OPTION) {
                        if (staffBank.isSelected()) {
                            StaffBankForm staffForm = new StaffBankForm();
                            staffForm.setVisible(true);
                            staffForm.DisplayInfo(creditCard);
                            staffForm.show();
                            this.dispose();
                        } else if (users.isSelected()) {
                            acountBank.DisplayInfo(creditCard);
                            acountBank.setVisible(true);
                            acountBank.show();
                            this.dispose();
                        }
                    } else if (option == JOptionPane.CANCEL_OPTION) {
                        // Cancel was pressed. Now do stuff.
                    }
                } else if (creditCard != null && !creditCard.getStaffBank()) {
                    acountBank.DisplayInfo(creditCard);
                    acountBank.setVisible(true);
                    acountBank.show();
                    this.dispose();
                }
            } else {
                JOptionPane.showMessageDialog(this,
                        "Nhập sai mật khẩu vui lòng nhập lại!",
                        "Lỗi đăng nhập",
                        JOptionPane.ERROR_MESSAGE);
            }
        } else {
            boolean check = accountName.matches("\\d{4}(-\\d{4}){3}");
            if(check)
            {
                boolean result = connectManager.loginSavingAccount(accountName);
                if(result)
                {
                    SavingAccount savingAccount = new SavingAccount();
                    SavingAccountObject object = connectManager.getInfoSavingAccount(accountName);
                    savingAccount.displayInfoSavingAccount(object);
                    savingAccount.setVisible(true);
                    savingAccount.show();
                    this.dispose();
                }else
                {
                    JOptionPane.showMessageDialog(this,
                        "Tài khoản không tồn tại!",
                        "Lỗi đăng nhập",
                        JOptionPane.ERROR_MESSAGE);
                }
            }else
            {
                 JOptionPane.showMessageDialog(this,
                        "Tài khoản phải đúng định dạnh xxxx-xxxx-xxxx-xxxx!",
                        "Lỗi tài khoản",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_jBtnLoginActionPerformed

    private void jChbSavingAccountActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jChbSavingAccountActionPerformed
        // TODO add your handling code here:
        if (jChbSavingAccount.isSelected()) {
            jLblPass.setVisible(false);
            jTxtPassWord.setVisible(false);
            validate();
        } else {
            jLblPass.setVisible(true);
            jTxtPassWord.setVisible(true);
            validate();
        }
    }//GEN-LAST:event_jChbSavingAccountActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>



        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Login(null).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBtnLogin;
    private javax.swing.JCheckBox jChbSavingAccount;
    private javax.swing.JLabel jLblAccountNumber;
    private javax.swing.JLabel jLblPass;
    private javax.swing.JPanel jPnLogin;
    private javax.swing.JTextField jTxtAccount;
    private javax.swing.JPasswordField jTxtPassWord;
    // End of variables declaration//GEN-END:variables
}
